function listToTree(list) {
  const map = {}
  const tree = []
  list.forEach(item => {
    map[item.id] = {...item, children: []}
  })
  list.forEach(item => {
    if(item.parentId == null) {
      tree.push(map[item.id])
    }else {
      const parent = map[item.parentId]
      parent && parent.children.push(map[item.id])
    }
  })
  return tree
}
const list = [
  { id: 1, name: '部门A', parentId: null },
  { id: 2, name: '部门B', parentId: 1 },
  { id: 3, name: '部门C', parentId: 1 },
  { id: 4, name: '部门D', parentId: 2 },
  { id: 5, name: '部门E', parentId: null },
];

const tree = listToTree(list);
console.log(JSON.stringify(tree, null,2));